package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.common.constants.behavior.BehaviorConstants;
import com.heima.common.constants.mess.app.UpdateArticleMess;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Resource
    ApBehaviorEntryService behaviorEntryService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null){
//            用户已登录，使用userId
            ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry == null){
                log.error("readBehavior 1  获取用户行为实体失败,userID为{},equipmentId为{}",user.getId(),dto.getEquipmentId());
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            return operationRead(behaviorEntry,dto);
        }
//        用户未登录,使用设备ID
        ApBehaviorEntry behaviorEntry = behaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        if (behaviorEntry == null){
            log.error("like 3  获取用户行为实体失败,userID为{},equipmentId为{}",null,dto.getEquipmentId());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return  operationRead(behaviorEntry,dto);
    }

    private ResponseResult operationRead(ApBehaviorEntry behaviorEntry, ReadBehaviorDTO dto) {
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        Long articleId = dto.getArticleId();
        Query query = Query.query(Criteria.where("articleId").is(articleId).and("entryId").is(behaviorEntry.getId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (readBehavior == null){
//            无阅读行为,则生成行为并保存
            readBehavior = new ApReadBehavior();
            readBehavior.setCount((short) 1);
            readBehavior.setCreatedTime(new Date());
            readBehavior = mongoTemplate.save(readBehavior);

//            阅读保存成功，发送MQ消息
            updateArticleMess.setArticleId(readBehavior.getArticleId());
            updateArticleMess.setAdd(1);
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
            rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE,JSON.toJSONString(updateArticleMess));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
//        有阅读行为,则计数＋1
        readBehavior.setCount((short) (readBehavior.getCount()+1));
        mongoTemplate.save(readBehavior);

//        阅读保存成功，发送MQ消息
        updateArticleMess.setArticleId(readBehavior.getArticleId());
        updateArticleMess.setAdd(1);
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(updateArticleMess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
